package calendar;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;

import javax.naming.Context;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.multimedia.jolitorask.client.ClientLocal;
import org.multimedia.jolitorask.client.ClientLocalHome;
import org.multimedia.jolitorask.extension.calendar.CalendarWrapperLocal;
import org.multimedia.jolitorask.extension.calendar.CalendarWrapperLocalHome;
import org.multimedia.jolitorask.utilisateur.UtilisateurLocal;

public class DeleteCalendar extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private static final String JNDI_NAME_WRAPPER = "calendarWrapperSessionLocal";
	private static final String JNDI_NAME_CLIENT = "clientLocal";
	
	public DeleteCalendar() {
		super();
	}   	
	
	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {


	    res.setContentType("text/plain");
	    PrintWriter out = res.getWriter();
	    
	    String account = req.getParameter("account");
	    String login = req.getParameter("login");
	    
	    if(account==null||login==null){
	    	out.println(false);
	    	return;
	    }

	    
	    /* Creation */
	    Context initContext = null;
	    Hashtable env = new Hashtable(1);
	    Object beanObject = null;
	    
	    	
	    try {
	    	initContext = new javax.naming.InitialContext(env);
	    	beanObject = initContext.lookup(JNDI_NAME_CLIENT);
	    	ClientLocalHome home = (ClientLocalHome) beanObject;
			
			Collection<ClientLocal> c = home.findByLogin(account);
			
			if(c == null || c.isEmpty() ){
				out.println(false);
				return;
			}
			
			ClientLocal client = c.iterator().next();
			Collection<UtilisateurLocal> liste = client.getUtilisateurs();
			
			Iterator<UtilisateurLocal> it = liste.iterator();
			
			UtilisateurLocal user = null;
			while( it.hasNext() ){
				UtilisateurLocal u = it.next();
				
				if(u.getLogin().equals(login)){
					user = u;
					break;
				}
					
			}
			
			if( user == null){
				out.println(false);
				return;
			}
			
			// supression du calendar
			initContext = new javax.naming.InitialContext(env);
	    	beanObject = initContext.lookup(JNDI_NAME_WRAPPER);
	    	
	    	CalendarWrapperLocal calendar = ((CalendarWrapperLocalHome)beanObject).create();
	    	
	    	calendar.deleteCalendar(((Integer)user.getPrimaryKey()).intValue());


	    }catch (Exception e) {
			out.println(false);
			e.printStackTrace();
	    	return;
		}

	    
	    
	    out.println(true);
	    
	}
}
